package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.utils.FileUploader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传和下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
/*

    @Value("${reggie.path}")
    private String basePath;

    */
/**
     * 文件上传
     *
     * @param file
     * @return
     *//*

    @PostMapping("upload")
    public R<String> upload(MultipartFile file) {
        String filename = null;
        try {
            // 将临时文件转存到本地磁盘
            //1. 获取原始文件名
            String originalFilename = file.getOriginalFilename();  // a.b.c.jpg

            //2. 对原始文件, 重新命名 --> 防止同名文件被覆盖
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            filename = UUID.randomUUID().toString() + suffix;

            //3. 对文件上传目录, 做了健壮性判断
            File f = new File(basePath);
            if (!f.exists()) {
                f.mkdirs();
            }
            //4. 转存到指定文件
            file.transferTo(new File(basePath + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return R.success(filename);

    }


    */
/**
     * 文件下载
     *
     * @param name
     *//*

    @GetMapping("download")
    public void download(String name,HttpServletResponse response) {
        try {
            //1. 读取磁盘文件, 获取输入流
            FileInputStream fis = new FileInputStream(basePath + name);

            //2. 获取响应字节输出流
            ServletOutputStream sos = response.getOutputStream();

            //3. IO流对拷
            IOUtils.copy(fis,sos);

            //4. 释放资源
            sos.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
*/


    @Autowired
    private FileUploader fileUploader;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        String fileName = null;
        try {
            fileName = fileUploader.upload(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

}
